package mongodb;

import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.util.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import static configure.InputConfig.*;

public class InputData {

    public static void main(String[] args) {
        mongoDataIn();
        //showIds();
    }

    public static void insertIntoMongo(File file, String collect, String caseTargetId) {
        String json = "";
        LinkedList<Object> list = new LinkedList<>();
        try {
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
            list = (LinkedList<Object>)inputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        for(Object object : list){
            //System.out.println(list.toString());

            String newString = object.toString().replace("\"null\"","null");
            DBObject bson = (DBObject) JSON.parse(newString);
            //System.out.println(bson.toString());
            updateMongo(bson, collect, caseTargetId);
        }
    }

    public static void updateMongo(DBObject insertDBObject, String collectionName, String caseTargetId) {
        try {
            //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址

            MongoClient mongoClient = new MongoClient(HOST, PORT);
            //连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase(DATABASE);
            //选择集合
            MongoCollection<DBObject> collection = mongoDatabase.getCollection(collectionName, DBObject.class);

            collection.findOneAndDelete(Filters.eq(caseTargetId, insertDBObject.get(caseTargetId)));

            collection.insertOne(insertDBObject);
            System.out.println(insertDBObject.toString());

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
    }

    public static void mongoDataIn() {
        File file = new File(MONGO_FILEPATH_CASE + MONGO_FILENAME_CASE);
        insertIntoMongo(file, COLLECTION_CASE, "caseId");
        file = new File(MONGO_FILEPATH_TARGET + MONGO_FILENAME_TARGET);
        insertIntoMongo(file, COLLECTION_TARGET, "targetId");
    }

    public static void showIds() {
        try {
            //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
            //ServerAddress()两个参数分别为 服务器地址 和 端口
            /*ServerAddress serverAddress = new ServerAddress(HOST, PORT);
            List<ServerAddress> addrs = new ArrayList<>();
            addrs.add(serverAddress);
            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
            MongoCredential credential = MongoCredential.createScramSha1Credential(USERNAME, DATABASE, PASSWORD.toCharArray());
            List<MongoCredential> credentials = new ArrayList<>();
            credentials.add(credential);
            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(addrs, credentials);
            */
            MongoClient mongoClient = new MongoClient(HOST, PORT);
            //连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase(DATABASE);
            //选择集合
            MongoCollection<DBObject> collection = mongoDatabase.getCollection("caseGraph", DBObject.class);
            //读出集合中的数据
            FindIterable<DBObject> findIterable = collection.find();
            MongoCursor<DBObject> mongoCursor = findIterable.iterator();
            //存放本地mongo中已有的caseId或targetId
            LinkedList<String> caseIdsInTable = new LinkedList<>();
            if (mongoCursor.hasNext()) {
                //取出case数组或target数组
                DBObject rs = mongoCursor.next();
                System.out.println("正在对数据进行格式化");
                JSONArray array = JSONArray.fromObject(rs.get("_embedded"));
                //记录本地mongo中已有的caseId或targetId
                for (Object object : array) {
                    System.out.println(JSONObject.fromObject(object).get("caseId"));
                }

            } else {
                System.out.println("nothing");
            }
            System.out.println("end");
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
    }
















/*

//ServerAddress()两个参数分别为 服务器地址 和 端口
            /*
            ServerAddress serverAddress = new ServerAddress(HOST, PORT);
            List<ServerAddress> addrs = new ArrayList<>();
            addrs.add(serverAddress);
            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
            MongoCredential credential = MongoCredential.createScramSha1Credential(USERNAME, DATABASE, PASSWORD.toCharArray());
            List<MongoCredential> credentials = new ArrayList<>();
            credentials.add(credential);
            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(addrs, credentials);
            */
//读出集合中的数据
    //FindIterable<DBObject> findIterable = collection.find();
    //MongoCursor<DBObject> mongoCursor = findIterable.iterator();
    //存放本地mongo中已有的caseId或targetId
    //LinkedList<String> caseIdsInTable = new LinkedList<>();
/*
//System.out.println("yes");
                //取出case数组或target数组
                DBObject rs = mongoCursor.next();
                System.out.println("正在对数据进行格式化");
                JSONArray array = JSONArray.fromObject(rs.get("_embedded"));
                //记录本地mongo中已有的caseId或targetId
                for (Object object : array) {
                    caseIdsInTable.add(JSONObject.fromObject(object).get(caseTargetId).toString());
                }
                //取出要导入的对象的case或target数组
                System.out.println("正在对数据进行格式化");
                JSONArray insertArray = JSONArray.fromObject(insertDBObject.get("_embedded"));
                //与本地数组进行比较，不在则插入
                for (Object object : insertArray) {
                    //不存在则插入
                    if (!caseIdsInTable.contains(JSONObject.fromObject(object).get(caseTargetId).toString())) {
                        array.add(object);
                    } else {
                        //存在则删除原来的，插入新的
                        for (int i = 0; i < array.size(); i++) {
                            String oldId = JSONObject.fromObject(array.get(i)).get(caseTargetId).toString();
                            String newId = JSONObject.fromObject(object).get(caseTargetId).toString();
                            if (oldId.equals(newId)) {
                                array.remove(i);
                                array.add(object);
                                break;
                            }
                        }
                    }
                }
                //删除原数组
                rs.removeField("_embedded");
                //放入新数组
                rs.put("_embedded", array.toString());
                //写回本地mongo
                collection.findOneAndReplace(Filters.eq("_id", rs.get("_id")), rs);
 */



    /*public static void main( String args[] ){
        //不用密码
        //连接mongodb服务和数据库
        try{
            // 连接到 mongodb 服务
            MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

            // 连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("sun");

        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }*/
}
